package com.wesley.fritesfinder.parser;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import android.sax.RootElement;

import com.wesley.fritesfinder.model.ActionPoint;
import com.wesley.fritesfinder.model.FoodShop;

public class FritesHandler extends DefaultHandler{
	// names of xml tags
	static final String ROOT = "actionPointList";
	static final String NAME = "name";
	static final String FOODSHOP = "foodshop";
	static final String POINT_LONGITUDE = "pointLongitude";
	static final String POINT_LATITUDE = "pointLatitude";
	static final String RATING = "rating";
	
	private ArrayList<FoodShop> fritesList;
	
	private StringBuffer buffer = null;
	private boolean readingContent = false;
	private FoodShop currentFoodshop;
	private URL url;
	
	
	@Override
	public void startDocument() throws SAXException {
		fritesList = new ArrayList<FoodShop>();
	}
	
	@Override
	public void endDocument() throws SAXException {
		// TODO Auto-generated method stub
		super.endDocument();
	}
	
	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		if(qName.equalsIgnoreCase(FOODSHOP)) {
			currentFoodshop = new FoodShop();
			buffer = new StringBuffer("");
			readingContent = true;
		}
	}
	
	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		// TODO Auto-generated method stub
		if(readingContent)
			buffer.append(ch, start, length);
	}
	
	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		if(qName.equalsIgnoreCase(NAME)) {
			currentFoodshop.setName(buffer.toString());
		} else if(qName.equalsIgnoreCase(RATING)) {
			String r = buffer.toString();
			try {
				currentFoodshop.setRating(new Double(r));
			} catch(NumberFormatException e) {
				currentFoodshop.setRating(-1);
			}
		} else if(qName.equalsIgnoreCase(POINT_LATITUDE)) {
			String latitude = buffer.toString();
			try {
				currentFoodshop.setLatitude(new Double(latitude));
			} catch(NumberFormatException e) {
				currentFoodshop.setRating(-1);
			}
		} else if(qName.equalsIgnoreCase(POINT_LONGITUDE)) {
			String longitude = buffer.toString();
			try {
				currentFoodshop.setLatitude(new Double(longitude));
			} catch(NumberFormatException e) {
				currentFoodshop.setRating(-1);
			}
		}
	}

	public ArrayList<FoodShop> retrieveFoodshopList() {
		return fritesList;
	}
	
}
